var ns, bmLocation,trans,WXPhotoPicker;
var app = new Vue({
    el: '#app',
    data: {
        form: {
            ID: 0,
            RegionName: '',
            ProjectName: '',
            CheckTime: '',
            InChargeManName: '',
            CheckStatus: 1,
            TaskCompleteContent: '',
            GPSLocation: ''
        },
        PlanType: 4,
        imglist: [],
        standardlist: [],
        maxuploadcount: CONFIG.maxuploadcount,
        IsAllowWatermark:false,
        IsLoadWatermark:false,
        planform: {
            TaskStatus:1,
        },
    },
    methods: {
        get_data: function() {
            var that = this;
            var options = {};
            options.action = "getequipmenttaskdevicedata";
            options.ID = that.form.ID;
            options.PlanType = that.PlanType;
            // console.log(JSON.stringify(options));
            ns.post(options, function(succeed, data, err) {
                // console.log(JSON.stringify(data));
                if (succeed) {
                    that.form = data.formdata;
                    //环境保洁大任务状态-已完成是2-加个1
                    that.planform.TaskStatus= data.formdata.PlanTaskStatus==undefined?that.form.TaskStatus: Number(data.formdata.PlanTaskStatus)+1; 
                    that.standardlist = data.standardlist;
                    that.imglist = data.imglist;
                    that.getIsAllowWatermark();//获取是否只调用相机权限
                    that.StartBmap();//获取定位
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true
            });
        },
        do_save: function() {
            var that = this;
            if (that.form.IsAllowUpload && that.imglist.length == 0) {
                api.toast({
                    msg: '请上传图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            that.do_save_process(0);
        },
        reload_list: function() {
            api.sendEvent({
                name: 'devicetaskcomplete',
            });
        },
        do_save_process: function(ServiceStatus) {
            var that = this;
            var options = {};
            options.action = "saveequipmenttaskdevicedata";
            options.ID = that.form.ID;
            options.CheckStatus = that.form.CheckStatus;
            options.GPSLocation = that.form.GPSLocation;
            options.ServiceStatus = ServiceStatus;
            options.TaskCompleteContent = that.form.TaskCompleteContent;
            options.PlanType = that.PlanType;
            var filelist = [];
            for (var i = 0; i < that.imglist.length; i++) {
                if (that.imglist[i].isupload) {
                    filelist.push(that.imglist[i].url);
                }
            }
            ns.post(options, function(succeed, data, err) {
                if (succeed) {
                    api.toast({
                        msg: '操作成功',
                        duration: 2000,
                        location: 'bottom'
                    });
                    that.reload_list();
                    setTimeout(function() {
                        api.closeWin();
                    }, 1000)
                    return
                } else if (err) {
                    api.toast({
                        msg: err,
                        duration: 2000,
                        location: 'bottom'
                    });
                }
            }, {
                toast: true,
                files: {
                    file: filelist
                }
            });
        },
        choose_picture: function() {
            var that = this;
            if (!that.IsLoadWatermark) {
                return;
            }
            setTimeout(function(){
                ns.confirmPer('camera', function() {
                    if (that.IsAllowWatermark) {
                        that.upload_choose_picture();
                    }
                    else {
                        that.choose_picture_start();
                    }
                })
            },300);    
        },
        choose_picture_start:function(){
            var that = this;
            if (that.imglist.length >= that.maxuploadcount) {
                api.toast({
                    msg: '最多支持' + that.maxuploadcount + '张图片',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            }
            api.actionSheet({
                cancelTitle: '取消',
                buttons: ['拍照', '从相册选择']
            }, function(ret, err) {
                //拍照
                if(ret.buttonIndex==1){ 
                    that.upload_choose_picture();
                    return;
                }
                //从相册选择
                if(ret.buttonIndex==2){
                    that.choose_picture_album();
                    return;
                } 
                //取消 
                else{
                    return false;  
                }  
            });
        },
        choose_picture_album:function(){
            var that = this;
            WXPhotoPicker.open({
                max: that.maxuploadcount - that.imglist.length,
                type:'image',
            }, function(ret) {
                if (ret) {
                    if (ret.list.length > 0) {
                        ret.list.forEach((item) => {
                            that.imglist.push({
                                ID: 0,
                                url: item.path,
                                thumbPath: item.path,
                                isupload: true
                            });
                        });
                    }
                }
            });
        },
        remove_img: function (index,item) {
            var that = this;
            that.imglist.splice(index, 1);
            if (item.ID > 0) {
                that.do_remove_uploadimg(item);
            }
        },
        do_remove_uploadimg: function(item) {
            var that = this;
            var options = {
                action: 'doremoveproductimg',
                ID: item.ID,
            }
            ns.post(options, function(succeed, data, err) {});
        },
        StartBmap: function() {
            var that = this;
            if (that.planform.TaskStatus == 3) {
                return;
            }
            ns.confirmPer('location', function() {
                that.StartLocation();
            })
        },
        StartLocation: function() {
            var that = this;
            if (that.planform.TaskStatus == 3) {
                return;
            }
            var num = 0; //次数
            that.form.GPSLocation = '';
            bmLocation.stopLocation();
            bmLocation.singleLocation({
                reGeocode: true,
                netWorkState: true
            }, function(ret) {
                if (ret.status) {
                    var locationDescribe=ns.DealLocationDescribe(ret.reGeo.locationDescribe);
                    that.form.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        ret.reGeo.district + ret.reGeo.street + ret.reGeo.streetNumber + locationDescribe;
                        // if (ret.reGeo.poiList != undefined && ret.reGeo.poiList.length > 0) {
                        //     that.form.GPSLocation = ret.reGeo.province + ret.reGeo.city +
                        //         ret.reGeo.district + ret.reGeo.street + ret.reGeo.poiList[0].name;
                        // }
                }
            });
        },
        configManager: function() {
            bmLocation.configManager({
                // accuracy: 'hight_accuracy',
                filter: 1,
                activityType: 'automotiveNavigation',
                coordinateType: 'BMK09LL',
                locationTimeout: 10,
                reGeocodeTimeout: 10
            });
        },
        do_viewimages: function(activeIndex) {
            var that = this;
            var imageUrls = [];
            for (var i = 0; i < that.imglist.length; i++) {
                imageUrls.push(that.imglist[i].url);
            }
            var imageBrowser = api.require('imageBrowser');
            imageBrowser.openImages({
                showList: false,
                activeIndex: activeIndex,
                imageUrls: imageUrls
            });
        },
        //获取是否只调用相机权限
        getIsAllowWatermark:function(){
            var that = this;
            if (!that.form.ProjectID) {
                return;
            }
            var options = {
                action: 'getplanparam',
                ProjectID:that.form.ProjectID,
                ConfigKey:'BJPhotoUse'
            };
            that.IsLoadWatermark=false;
            ns.post(options, function (succeed, data, err) {
                that.IsLoadWatermark=true;
                if (succeed) {
                    that.IsAllowWatermark = data.type == 2 ? true : false;
                }
            });
        },
        // 系统只调用相机 并添加水印
        upload_choose_picture:function(){
            var that = this;
            api.getPicture({
                sourceType: 'camera',
                encodingType: 'jpg',
                destinationType: 'url',
                allowEdit: false,
                saveToPhotoAlbum: that.IsAllowWatermark?false:true,
            }, function(ret, err) {
                if (ret&&ret.data) {
                    if (that.IsAllowWatermark) {
                        that.waterMark(ret.data);
                        return;
                    }
                    else {
                        that.imglist.push({
                            ID: 0,
                            url: ret.data,
                            thumbPath: ret.data,
                            isupload: true
                        });
                    }
                } 
            });
        },
        waterMark: function (imagePath) {
            var that = this;
            if(!imagePath){
                api.toast({
                    msg: '图片地址为空',
                    duration: 2000,
                    location: 'bottom'
                });
                return;
            } 
            var imageName =imagePath.split('/').pop(); //获取图片名称
            var dateTime = moment().format('YYYY-MM-DD HH:mm:ss');
            // 调用生成水印方法  返回Base64图片格式
            ns.setWatermark(imagePath, '环境保洁水印', dateTime, that.form.GPSLocation).then((value) => {
                var base64Str=value;
                if (base64Str) {
                    //Base64图片 转jpg、png格式
                    trans.saveImage({
                        base64Str: base64Str,
                        // album:true,
                        imgPath: "fs://watermark/",
                        imgName: imageName
                    }, function (ret, err) {
                        if (ret.status) {
                            var newImagePath=api.fsDir + '/'+'watermark'+'/'+imageName;
                            that.imglist.push({
                                ID: 0,
                                url:newImagePath,
                                thumbPath: newImagePath,
                                isupload: true
                            });
                             //水印图片-保存到相册
                             api.saveMediaToAlbum({
                                path: 'fs://watermark/'+imageName
                            }, function(ret, err) {
                            });
                        } else {
                            api.toast({
                                msg: '水印图片保存本地失败！',
                                duration: 2000,
                                location: 'bottom'
                            });
                            return;
                        }
                    });
                }else{
                    // api.toast({
                    //     msg: '生成水印失败！',
                    //     duration: 2000,
                    //     location: 'bottom'
                    // });
                    that.imglist.push({
                        ID: 0,
                        url: imagePath,
                        thumbPath: imagePath,
                        isupload: true
                    });
                    return;
                }   
            }) 
        },
    }
});
apiready = function() {
    api.parseTapmode();
    WXPhotoPicker = api.require('WXPhotoPicker');
    bmLocation = api.require('bmLocation');
    trans = api.require('trans');
    ns = window.Foresight.Util;
    app.form.ID = api.pageParam.id || 0;
    toast = new auiToast();

    setTimeout(function() {
        app.configManager();
        // app.StartBmap();
    }, 1000)
    setTimeout(function() {
        app.get_data();
    }, 500)
    bmLocation.setAgreePrivacy({
        agree: true
    });
}
